package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import com.usian.utils.common.exception.CatchCustomException;
import com.usian.utils.common.exception.code.UserStatusCode;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceimpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDto dto) {
        //检查参数，
        //1.检查参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"用户名密码不能为空");
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码错误");
        }
        //根据用户获取信息
        WmUser wmUser = this.getOne(new LambdaQueryWrapper<WmUser>().eq(WmUser::getName, dto.getName()));
        if (wmUser==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"用户名错误");
        }
        //登录成功
        if (!BCrypt.checkpw(dto.getPassword(),wmUser.getPassword())){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"密码错误");
        }
        //签发令牌
        String token = AppJwtUtil.getToken(Long.parseLong(wmUser.getId() + ""));
        //4.返回数据jwt
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        wmUser.setSalt("");
        map.put("user",wmUser);
        return ResponseResult.okResult(map);
    }
}
